package com.example.myapplication

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import java.io.File

@Composable
fun Config() {
    val context = LocalContext.current
    var permissionGranted by remember { mutableStateOf(false) }
    var displayPath by remember {
        mutableStateOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).absolutePath)
    }
    //var selectedDir by remember {
    //    mutableStateOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))
    //}

    val permissionLauncher = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        permissionGranted = granted
        if (granted) {
            scanFolder(context, StaticStorage.Lib)
        } else {
            Toast.makeText(context, "无权限", Toast.LENGTH_SHORT).show()
        }
    }

    val dirPicker = rememberLauncherForActivityResult(
        ActivityResultContracts.OpenDocumentTree()
    ) { uri ->
        uri?.let {
            val path = extractPathFromTreeUri(it)
            if (!path.isNullOrEmpty()) {
                val file = File(path)

                if (file.exists() && file.isDirectory)
                {
                    StaticStorage.Lib = file
                    val pref = context.getSharedPreferences("LibPath", Context.MODE_PRIVATE);
                    pref.edit().putString("LibPath", StaticStorage.Lib.toString()).apply();
                    displayPath = file.absolutePath
                    if (permissionGranted)
                    {
                        scanFolder(context, file)
                    }
                }
                else
                {
                    Toast.makeText(context, "无效目录", Toast.LENGTH_SHORT).show()
                }
            }
            else
            {
                Toast.makeText(context, "无法获取路径", Toast.LENGTH_SHORT).show()
            }
        }
    }

    LaunchedEffect(Unit) {
        val granted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        }
        permissionGranted = granted
        if (granted) {
            scanFolder(context, StaticStorage.Lib)
        } else {
            permissionLauncher.launch(
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
                    Manifest.permission.READ_MEDIA_AUDIO
                else
                    Manifest.permission.READ_EXTERNAL_STORAGE
            )
        }
    }

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text("音乐库设置", style = MaterialTheme.typography.titleLarge)
        Spacer(Modifier.height(16.dp))

        Row{
            Spacer(Modifier.weight(0.1f))
            Box(Modifier.fillMaxWidth().weight(1.2f).height(70.dp))
            {
                OutlinedTextField(
                    value = displayPath,
                    onValueChange = {},
                    readOnly = true,
                    label = { Text("当前路径") },
                    modifier = Modifier.fillMaxSize(),
                    singleLine = true)

                Box(Modifier.clickable{dirPicker.launch(null)}.fillMaxSize())
            }
            Spacer(Modifier.weight(0.1f))
        }


        Spacer(Modifier.height(12.dp))

        Row {
            Spacer(Modifier.weight(0.1f))
            Button(
                onClick = {
                    if (permissionGranted) {
                        scanFolder(context, StaticStorage.Lib)
                        Toast.makeText(context, "扫描完成，共${StaticStorage.musicList.size}首",
                            Toast.LENGTH_SHORT).show()

                    } else {
                        permissionLauncher.launch(
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
                                Manifest.permission.READ_MEDIA_AUDIO
                            else
                                Manifest.permission.READ_EXTERNAL_STORAGE
                        )
                    }
                },
                enabled = permissionGranted,
                modifier = Modifier.weight(1.2f)
            ) {
                Text("重新扫描")
            }
            Spacer(Modifier.weight(0.1f))
        }

        Spacer(Modifier.height(24.dp))
    }
}

private fun extractPathFromTreeUri(treeUri: Uri): String? {
    return try {
        val docId = DocumentsContract.getTreeDocumentId(treeUri)
        val parts = docId.split(":", limit = 2)
        val (root, subPath) = if (parts.size == 1) parts[0] to "" else parts[0] to parts[1]

        val basePath = when (root) {
            "primary" -> Environment.getExternalStorageDirectory().absolutePath
            else -> "/storage/$root"
        }

        if (subPath.isEmpty()) {
            basePath
        } else {
            "$basePath/$subPath".replace("//", "/")
        }
    } catch (e: Exception) {
        null
    }
}

// 递归扫描目录
fun scanFolder(context: Context, dir: File) {
    StaticStorage.musicList.clear()
    traverseDir(dir)
    //Toast.makeText(context, "共 ${StaticStorage.musicList.size} 首", Toast.LENGTH_SHORT).show()
}

private fun traverseDir(dir: File) {
    dir.listFiles()?.forEach { file ->
        if (file.isDirectory) {
            traverseDir(file) // 递归
        } else if (file.isFile && isAudioFile(file.name)) {
            StaticStorage.musicList.add(file)
        }
    }
}

private fun isAudioFile(name: String): Boolean {
    val n = name.lowercase()
    return n.endsWith(".mp3") || n.endsWith(".flac") || n.endsWith(".wav") ||
            n.endsWith(".m4a") || n.endsWith(".aac") || n.endsWith(".ogg") ||
            n.endsWith(".wma") || n.endsWith(".ape")
}